<template>
  <div id="AddProduct">
    <!-- 配置规格参数的弹出框 -->
    <el-dialog
      title="规格配置"
      :visible.sync="specConfigVisible"
    >
      <el-form
        :model="specConfigForm"
        :rules="specConfigRule"
        ref="specConfigForm"
        label-width="100px">
        <el-form-item label="规格名称" prop="specName">
          <el-input type="text" v-model="specConfigForm.specName"></el-input>
        </el-form-item>
        <el-form-item label="原价" prop="originalPrice">
          <el-input type="number" v-model.number="specConfigForm.originalPrice">
            <template slot="suffix">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="现价" prop="discountPrice">
          <el-input type="number" v-model.number="specConfigForm.discountPrice">
            <template slot="suffix">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="积分价" prop="creditPrice">
          <el-input type="number" v-model.number="specConfigForm.creditPrice"></el-input>
        </el-form-item>
        <el-form-item label="库存" prop="inventory">
          <el-input type="number" v-model.number="specConfigForm.inventory"></el-input>
        </el-form-item>
        <el-form-item v-if="isSelectTicket" label="优惠券" prop="ticketId">
          <el-select
            v-model="specConfigForm.ticketId"
            placeholder="请选择优惠券"
            @change="onChangeTicket"
          >
            <el-option
              v-for="item in ticketList" :key="`tl1-${item.id}`"
              :label="`${item.name} 有效期：${item.begintime}至${item.endtime}`"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="specConfigClose('specConfigForm')">取 消</el-button>
        <el-button type="primary" @click="addOneSpec('specConfigForm')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改配置规格参数的弹出框 -->
    <el-dialog
      title="规格修改"
      :visible.sync="editSpecConfigVis">
      <el-form
        :model="specConfigForm"
        :rules="specConfigRule"
        ref="specConfigForm"
        label-width="100px">
        <el-form-item label="规格名称" prop="specName">
          <el-input type="text" v-model="specConfigForm.specName"></el-input>
        </el-form-item>
        <el-form-item label="原价" prop="originalPrice">
          <el-input type="number" v-model.number="specConfigForm.originalPrice">
            <template slot="suffix">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="现价" prop="discountPrice">
          <el-input type="number" v-model.number="specConfigForm.discountPrice">
            <template slot="suffix">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="积分价" prop="creditPrice">
          <el-input type="number" v-model.number="specConfigForm.creditPrice"></el-input>
        </el-form-item>
        <el-form-item label="库存" prop="inventory">
          <el-input type="number" v-model.number="specConfigForm.inventory"></el-input>
        </el-form-item>
        <el-form-item v-if="isSelectTicket" label="优惠券" prop="ticketId">
          <el-select
            v-model="specConfigForm.ticketId"
            placeholder="请选择优惠券"
            @change="onChangeTicket"
          >
            <el-option
              v-for="item in ticketList" :key="`tl2${item.id}`"
              :label="`${item.name} 有效期：${item.begintime}至${item.endtime}`"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="specConfigClose('specConfigForm')">取 消</el-button>
        <el-button type="primary" @click="editOneSpecOk('specConfigForm')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 保存/发布 确认对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="submitFormVisible"
      width="30%"
    >
      <span>确认{{submitFormTip}}？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="submitFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="postFromData" :loading="submitOkLoading">确 定</el-button>
      </span>
    </el-dialog>

    <main-header :title="headTitle" :crumbsArr="crumbsArr" />
    <div class="add_input_wrapper">
      <el-form :model="formData" :rules="rules" ref="formData" label-width="100px" v-loading="editLoading">
        <h4>基础信息</h4>
        <el-form-item label="商品ID" v-if="$route.params.isEdit">
          <span>{{formData.itemId}}</span>
        </el-form-item>
        <el-form-item label="商品名称" prop="item_name">
          <el-input type="text" v-model="formData.item_name"></el-input>
        </el-form-item>
        <el-form-item label="系列" prop="type">
          <el-select
            v-model="formData.type"
            placeholder="请选择系列"
            @change="seriesChangeHandle"
          >
            <el-option
              v-for="series in seriesList" :key="`s1-${series.id}`"
              :label="series.name"
              :value="series.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类别" prop="item_series_mapping">
          <el-select v-model="formData.item_series_mapping" placeholder="请选择类别">
            <el-option
              v-for="type in typeList" :key="`tyl${type.id}`"
              :label="type.name"
              :value="type.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="卖点">
          <el-input type="textarea" v-model="formData.item_sellingPoint"></el-input>
        </el-form-item>
        <el-form-item v-if="labelList" label="标签" prop="labelList">
          <el-checkbox-group v-model="formData.labelListArr">
            <el-checkbox
              v-for="label in labelList" :key="`ll1-${label.id}`"
              :label="label.id"
              name="labelList">
              {{label.name}}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="退款" prop="refund">
          <el-radio-group v-model="formData.refund">
            <el-radio label="1">支持</el-radio>
            <el-radio label="0">不支持</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="返现" prop="reward">
          <el-radio-group v-model="formData.reward">
            <el-radio label="1">支持</el-radio>
            <el-radio label="0">不支持</el-radio>
          </el-radio-group>
        </el-form-item>

        <h4>商品规格</h4>
        <el-button
          type="info" size="small" plain
          @click="addOneSpecClick">
          <i class="el-icon-plus"></i>添加规格
        </el-button>
        <spec-list-table
          :specList="specList"
          @deleteOneSpec="deleteOneSpec"
          @editOneSpec="editOneSpec"
          :isSelectTicket="isSelectTicket"
        />

        <h4>商品参数</h4>
        <el-form-item label="体积">
          <el-input
            v-model="formData.detail_volume"
            @change="validateNum($event, 'detail_volume')">
            <template slot="suffix">ml</template>
          </el-input>
        </el-form-item>
        <el-form-item label="产地">
          <el-input v-model="formData.detail_producingArea"></el-input>
        </el-form-item>
        <el-form-item label="生产日期">
          <el-form-item prop="detail_productionDate">
            <el-date-picker
              type="date" placeholder="选择日期"
              v-model="formData.detail_productionDate">
            </el-date-picker>
          </el-form-item>
        </el-form-item>
        <el-form-item label="保质期">
          <el-input
            v-model="formData.detail_shelfLife"
            @change="validateNum($event, 'detail_shelfLife')">
            <template slot="suffix">个月</template>
          </el-input>
        </el-form-item>

        <h4>图片配置</h4>
        <el-form-item label="缩略图" class="item_img_upload_wrapper">
          <ul v-loading="itemImgLoading">
            <li v-for="(pic, index) in itemPics" :key="`iI${index}`" :ref="pic.id">
              <div class="a_item_pic_block">
                <img width="100px" height="100px" :src="pic.picUrl | handleItemPicPath" alt="">
                <div class="hover_delete">
                  <el-button type="danger" icon="el-icon-delete" circle @click="deleteItemPic('itemPics', index)"></el-button>
                </div>
              </div>
            </li>
            <li v-if="itemPics.length < 2">
              <div>
                <input
                  ref="addItemPicInput"
                  type="file" name="itemFile"
                  style="display: none;"
                  accept="image/*"
                  @change="addPicInputChange('addItemPicInput')">
                <el-button
                  class="add_item_pic_btn"
                  @click="clickAddImg('addItemPicInput', 4)">
                  <i class="el-icon-plus"></i>
                </el-button>
              </div>
            </li>
          </ul>
          <div class="pci_tip">
            约定上传两张图片，第一张为正方形缩略图，第二张为宽度最少750像素的Banner图片
          </div>
        </el-form-item>
        <el-form-item label="商品详情图" class="detail_img_upload_wrapper">
          <ul v-loading="detailImgLoading">
            <li v-for="(pic, index) in detailPics" :key="`dI${index}`" :ref="pic.id">
              <div class="a_item_pic_block">
                <img width="200px" height="100px" :src="pic.picUrl | handleDetailPicPath" alt="">
                <div class="hover_delete">
                  <el-button type="danger" icon="el-icon-delete" circle @click="deleteItemPic('detailPics', index)"></el-button>
                </div>
              </div>
            </li>
            <li>
              <div>
                <input
                  ref="addDetailPicInput"
                  type="file" name="itemFile"
                  style="display: none;"
                  accept="image/*"
                  @change="addPicInputChange('addDetailPicInput')">
                <el-button
                  class="add_item_pic_btn"
                  @click="clickAddImg('addDetailPicInput', 10)">
                  <i class="el-icon-plus"></i>
                </el-button>
              </div>
            </li>
          </ul>
          <div class="pci_tip">
            最少上传1张，最多上传10张
          </div>
        </el-form-item>

        <h4>分销提点</h4>
        <el-form-item label="一级提点" ref="stairProfit">
          <el-input
            v-model="formData.stairProfit"
            @change="validateProfit($event, 'stairProfit')">
            <template slot="suffix">%</template>
          </el-input>
        </el-form-item>
        <el-form-item label="二级提点" ref="secondaryProfit">
          <el-input
            v-model="formData.secondaryProfit"
            @change="validateProfit($event, 'secondaryProfit')">
            <template slot="suffix">%</template>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="clickReleaseProduct('formData')">立即发布</el-button>
          <el-button @click="clickSaveProduct('formData')">保存商品</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import * as qiniu from 'qiniu-js'
import moment from 'moment'
import MainHeader from '@/components/layouts/MainHeader'
import API from '@/config/api.js'
import ErrorConfig from '@/config/error.config.js'
import SpecListTable from '@/components/pages/product/SpecListTable'

export default {
  name: 'AddProduct',
  data () {
    let validateNumNotEmpty = (rule, value, callback) => { // 自定义表单校验 校验不能为空的数值
      if (!Number.parseFloat(value)) {
        if (parseFloat(value) === 0) {
          callback()
        } else {
          callback(new Error('请输入正确的数值'))
        }
      } else {
        if (value < 0) {
          callback(new Error('请输入不小于0的数值'))
        } else {
          callback()
        }
      }
    }
    return {
      crumbsArr: [ // 面包屑
        { name: 'welcome', txt: '首页' }, { name: 'product', txt: '商品管理' }, { txt: '商品添加' }
      ],
      isSelectTicket: false,
      headTitle: '',
      emptyFormData: { // 表单数据
        itemId: null,
        item_name: '', // 商品名称
        item_series_mapping: '', // 类型的映射
        item_series: 0,
        type: '', // 系列
        item_sellingPoint: '', // 卖点
        labelListArr: [],
        labelList: [], // 标签列表
        refund: '1', // 退货
        reward: '1', // 返现
        detail_volume: '', // 体积
        detail_producingArea: '', // 产地
        detail_productionDate: '', // 生产日期
        detail_shelfLife: '', // 保质期
        stairProfit: null, // 一级提点
        secondaryProfit: null // 二级提点
      },
      formData: { // 表单数据
        itemId: null,
        item_name: '', // 商品名称
        item_series_mapping: '', // 类型的映射
        item_series: 0,
        type: '', // 系列
        item_sellingPoint: '', // 卖点
        labelListArr: [],
        labelList: [], // 标签列表
        refund: '1', // 退货
        reward: '1', // 返现
        detail_volume: '', // 体积
        detail_producingArea: '', // 产地
        detail_productionDate: '', // 生产日期
        detail_shelfLife: '', // 保质期
        stairProfit: null, // 一级提点
        secondaryProfit: null // 二级提点
      },
      rules: { // 表单验证规则
        item_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择系列', trigger: 'change' }
        ],
        item_series_mapping: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ]
      },
      specConfigForm: {
        thisEditIndex: null,
        specName: '', // 规格名称
        originalPrice: 0, // 原价
        discountPrice: 0, // 现价
        inventory: 0, // 库存
        creditPrice: 0, // 积分价
        operation: 1,
        isNewAdd: true,
        ticketId: '',
        ticketTxt: ''
      },
      specConfigFormEmpty: {
        thisEditIndex: null,
        specName: '', // 规格名称
        originalPrice: 0, // 原价
        discountPrice: 0, // 现价
        inventory: 0, // 库存
        creditPrice: 0, // 积分价
        operation: 1,
        isNewAdd: true,
        ticketId: '',
        ticketTxt: ''
      },
      ticketList: [],
      specList: [], // 规格列表
      specListWillDel: [],
      specConfigRule: {
        specName: [
          { required: true, message: '请输入规格名称', trigger: 'blur' }
        ],
        originalPrice: [
          { validator: validateNumNotEmpty, trigger: 'blur' }
        ],
        discountPrice: [
          { validator: validateNumNotEmpty, trigger: 'blur' }
        ],
        inventory: [
          { validator: validateNumNotEmpty, trigger: 'blur' }
        ],
        creditPrice: [
          { validator: validateNumNotEmpty, trigger: 'blur' }
        ],
        ticketId: [
          { required: true, message: '请选择优惠券', trigger: 'change' }
        ]
      },
      labelList: null, // 标签列表
      typeList: null, // 类别
      itemPics: [], // 缩略图列表
      detailPics: [], // 详情图列表
      seriesList: [ // 系列
        { id: 0, name: '商品' },
        { id: 1, name: '服务' },
        { id: 2, name: '礼品' },
        { id: 3, name: '兑换券' }
      ],
      imageUrl: '',
      specConfigVisible: false, // 控制规格配置dialog的显示隐藏
      isNeedShowTypeSelect: false, // 控制类型选择框的显示隐藏
      submitFormVisible: false, // 控制发布/保存dialog的显示隐藏
      submitFormTip: '',
      state: 0, // 商品发布/保存 0-保存 1-发布
      itemImgLoading: false,
      detailImgLoading: false,
      editSpecConfigVis: false,
      submitOkLoading: false,
      editLoading: false
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.initPage()
    })
  },
  watch: {
    'formData.item_series_mapping' (val, oldVal) {
      this.formData.item_series = val
    },
    '$route' (to, from) {
      // this.initPage()
      let arr = this.crumbsArr
      if (to.name === 'product_add') {
        this.initPage()
        arr[arr.length - 1].txt = '商品添加'
      }
      if (to.name === 'product_edit') {
        arr[arr.length - 1].txt = '商品编辑'
      }
      this.crumbsArr = Object.assign([], arr)
    }
  },
  filters: {
    handleItemPicPath: (value) => {
      return `${value}?imageView2/1/w/100/h/100`
    },
    handleDetailPicPath: (value) => {
      return `${value}?imageView2/1/w/200/h/100`
    }
  },
  methods: {
    async initPage () {
      this.itemPics = Object.assign([], [])
      this.detailPics = Object.assign([], [])
      this.specList = Object.assign([], [])
      this.$refs['formData'].resetFields() // 重置新增表单
      this.formData = Object.assign({}, this.emptyFormData)
      this.isSelectTicket = false
      this.getLabelList() // 初始化标签数据
      this.getTypeList() // 初始化系列数据
      this.getTicket() // 初始化优惠券数据
      if (this.$route.params.editItemId) { // 当前是编辑页面编辑
        this.editLoading = true
        const { editItemId } = this.$route.params
        const response = await API.showProductDetail({ id: editItemId })
        const { code } = response
        this.editLoading = false
        if (code === 1) {
          this.editPageInit(response.data)
        } else {
          if (code === -1) {
            const { msg } = response
            this.$message.error(msg)
          } else {
            this.$message.error(ErrorConfig[code])
          }
        }
      } else {
        this.headTitle = '添加商品'
      }
    },
    editPageInit (params) {
      this.headTitle = '编辑商品'
      let itemPics = []
      let detailPics = []
      /* 装配详情数据 start */
      this.formData.itemId = params.id
      this.formData.item_name = params.itemName
      this.formData.item_series_mapping = params.seriesId
      this.formData.item_series = params.seriesId
      this.formData.type = params.type
      this.formData.item_sellingPoint = params.sellingPoints
      let tempArr = []
      for (let item of params.saleLabels) {
        tempArr.push(item.labelId)
      }
      this.formData.labelListArr = Object.assign([], tempArr)
      this.formData.refund = params.refundFlag.toString()
      this.formData.reward = params.rewardFlag.toString()
      this.formData.detail_producingArea = params.saleItemDetail.producingArea
      this.specList = Object.assign([], params.saleItemSpecList)
      itemPics.push({
        id: new Date().getTime(),
        picUrl: params.avatar
      })
      for (let i = 1; i < 4; i++) {
        if (params['avatar' + (i + 1)] !== '') {
          itemPics.push({
            id: new Date().getTime(),
            picUrl: params['avatar' + (i + 1)]
          })
        }
      }
      this.itemPics = Array.from(new Set(itemPics))
      if (params.saleItemDetail) {
        this.formData.detail_productionDate = moment(params.saleItemDetail.productionDate)
        this.formData.detail_volume = params.saleItemDetail.volume
        this.formData.detail_shelfLife = params.saleItemDetail.shelfLife
        this.formData.detail_volume = params.saleItemDetail.volume
        for (let i = 0; i < 10; i++) {
          if (params.saleItemDetail['avatar' + (i + 1)] !== '') {
            detailPics.push({
              id: new Date().getTime(),
              picUrl: params.saleItemDetail['avatar' + (i + 1)]
            })
          }
        }
        this.detailPics = Array.from(new Set(detailPics))
      }
      if (params.itemProfit) {
        this.formData.stairProfit = params.itemProfit.profitUp * 100
        this.formData.secondaryProfit = params.itemProfit.profitUpUp * 100
      }
      /* 装配详情数据 end */
    },
    async getTicket () {
      const response = await API.queryTicket({ page: 1, rows: 100 })
      const { code } = response
      if (code === 1) {
        const { data } = response
        this.ticketList = data.rows
      } else {
        if (code === -1) {
          const { msg } = response
          this.$message.error(msg)
        } else {
          this.$message.error(ErrorConfig[code])
        }
      }
    },
    async getLabelList () { // 获取标签列表
      const response = await API.getLabelList()
      const { code } = response
      if (code === 1) {
        const { data } = response
        this.labelList = data
      } else {
        if (code === -1) {
          const { msg } = response
          this.$message.error(msg)
        } else {
          this.$message.error(ErrorConfig[code])
        }
      }
    },
    async getTypeList () { // 获取类别列表
      const response = await API.getTypeList({})
      const { code } = response
      if (code === 1) {
        const typeList = response.data
        this.typeList = typeList
      } else {
        if (code === -1) {
          const { msg } = response
          this.$message.error(msg)
        } else {
          this.$message.error(ErrorConfig[code])
        }
      }
    },
    specConfigClose (formName) { // 关闭规格配置面板时重置表单
      this.$refs[formName].resetFields()
      this.specConfigVisible = false
      this.editSpecConfigVis = false
    },
    addOneSpecClick () {
      this.specConfigForm = Object.assign({}, this.specConfigFormEmpty) // 重置表单
      this.specConfigVisible = true
    },
    addOneSpec (formName) { // 添加一行规格配置
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const specItem = Object.assign({}, this.specConfigForm)
          this.specList.push(specItem)
        } else {
          return false
        }
        this.$refs[formName].resetFields()
        this.specConfigVisible = false
      })
    },
    deleteOneSpec (index) { // 规格表格删除一行
      this.$confirm('确认删除该规格？')
        .then(_ => {
          if (this.headTitle === '编辑商品') {
            if (!this.specList[index].isNewAdd) {
              this.specList[index].operation = 3
              this.specListWillDel.push(this.specList[index])
            }
          }
          this.specList.splice(index, 1)
        })
        .catch(_ => {})
    },
    editOneSpec (index) {
      this.specConfigForm = Object.assign({}, this.specList[index])
      this.specConfigForm.thisEditIndex = index
      this.editSpecConfigVis = true
    },
    editOneSpecOk (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const { thisEditIndex } = this.specConfigForm // 当前编辑的那一条
          this.specList.splice(thisEditIndex, 1, Object.assign({}, this.specConfigForm))
          this.specList[thisEditIndex].operation = 2
          this.specConfigForm = Object.assign({}, this.specConfigFormEmpty) // 重置表单
        } else {
          return false
        }
        this.$refs['specConfigForm'].resetFields()
        this.editSpecConfigVis = false
      })
    },
    deleteItemPic (whichPic, index) { // 删除一张图片
      this[whichPic].splice(index, 1)
    },
    seriesChangeHandle (selectedVal) { // 系列选择框change事件，来控制类型选择的显示隐藏
      if (selectedVal === 1) { // 服务
        this.isNeedShowTypeSelect = true
      } else {
        this.isNeedShowTypeSelect = false
      }
      if (selectedVal === 3) { // 兑换券
        this.isSelectTicket = true
      } else {
        this.isSelectTicket = false
      }
    },
    validateNum (num, inputName) { // 系列选择框change事件，来控制类型选择的显示隐藏
      if (!num) return
      if (!Number.parseFloat(num)) {
        if (num !== 0) {
          this.formData[inputName] = ''
          this.$message.error('请输入正确的数值')
        }
      } else {
        if (num < 0) {
          this.formData[inputName] = ''
          this.$message.error('请输入不小于0的数值')
        }
      }
    },
    clickAddImg (inputName, num) { // 点击添加缩略图片按钮 出发隐藏的file input
      let whichPic = ''
      if (inputName === 'addItemPicInput') { // 缩略图
        whichPic = 'itemPics'
      } else {
        whichPic = 'detailPics'
      }
      if (this[whichPic].length === num) {
        this.$message.error(`只能上传${num}张图片`)
        return false
      }
      this.$refs[inputName].click()
    },
    async addPicInputChange (inputName) { // 选择图片 change事件
      if (!(this.$refs[inputName].files[0])) {
        return false
      }
      let whichPic = ''
      let whichLoading = ''
      if (inputName === 'addItemPicInput') { // 缩略图
        whichPic = 'itemPics'
        whichLoading = 'itemImgLoading'
      } else {
        whichPic = 'detailPics'
        whichLoading = 'detailImgLoading'
      }
      this[whichLoading] = true
      const response = await API.getQiNiuToken()
      const qiniuConfig = { // 七牛云上传参数
        file: this.$refs[inputName].files[0],
        key: new Date().getTime(),
        token: response.data,
        putExtra: {
          fname: '',
          params: {},
          mimeType: [] || null
        },
        config: {
          useCdnDomain: true
        }
      }

      // 注入七牛参数
      let observable =
        qiniu.upload(qiniuConfig.file, qiniuConfig.key, qiniuConfig.token, qiniuConfig.putExtra, qiniuConfig.config)

      // 开始上传
      observable.subscribe(undefined, (errmsg) => {
        this[whichLoading] = false
        this.$message.error('图片上传失败，请重试')
      }, async (res) => {
        this[whichPic].push({
          id: new Date().getTime(),
          picUrl: `${API.FILE_HOST_URL}${res.key}`
        })
        this[whichLoading] = false
      })
      this.$refs[inputName].value = ''
    },
    clickReleaseProduct (formName) { // 点击发布商品按钮
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.specList.length === 0) {
            this.$message({
              type: 'warning',
              message: '请至少添加一条规格'
            })
            return false
          }
          if (this.itemPics.length === 0) {
            this.$message({
              type: 'warning',
              message: '请添加缩略图片'
            })
            return false
          }
          if (this.detailPics.length === 0) {
            this.$message({
              type: 'warning',
              message: '请添加详情图片'
            })
            return false
          }
          if (this.itemImgLoading || this.detailImgLoading) {
            this.$message.error('请等待图片上传完成')
            return false
          }
          // 弹出确认框
          this.state = 1
          this.submitFormTip = '发布'
          this.submitFormVisible = true
        } else {
          return false
        }
      })
    },
    clickSaveProduct (formName) { // 点击保存商品按钮
      let _self = this
      if (this.itemPics.length === 0) {
        this.$message({
          type: 'warning',
          message: '请添加缩略图片'
        })
        return false
      }
      if (this.detailPics.length === 0) {
        this.$message({
          type: 'warning',
          message: '请添加详情图片'
        })
        return false
      }
      _self.$refs[formName].validate((valid) => {
        if (valid) {
          // 弹出确认框
          _self.state = 0
          _self.submitFormTip = '保存'
          _self.submitFormVisible = true
        } else {
          return false
        }
      })
    },
    async postFromData () { // 提交表单数据
      this.submitOkLoading = true
      let formData = Object.assign({}, this.formData)
      let specList = Object.assign([], this.specList)
      if (formData.detail_productionDate !== '') {
        formData.detail_productionDate = moment(formData.detail_productionDate).format('YYYY-MM-DD') // 过滤时间 转为字符串
      }
      formData.specList = specList
      formData.state = this.state
      if (formData.stairProfit !== null) {
        formData.stairProfit = formData.stairProfit / 100
      }
      if (formData.secondaryProfit !== null) {
        formData.secondaryProfit = formData.secondaryProfit / 100
      }
      if (formData.labelListArr.length > 0) { // 注入标签列表数据
        formData.labelList = []
        for (let item of formData.labelListArr) {
          formData.labelList.push({
            id: item
          })
        }
      }

      this.itemPics.forEach(function (item, idx, arr) { // 注入缩略图
        formData[`item_img${idx + 1}`] = item.picUrl
      })
      this.detailPics.forEach(function (item, idx, arr) { // 注入详情图
        formData[`detail_img${idx + 1}`] = item.picUrl
      })

      let response = null

      if (this.headTitle === '编辑商品') {
        formData.specList = formData.specList.concat(this.specListWillDel) // 编辑商品时需记录被删掉的规格
        response = await API.editProduct(formData)
      } else {
        response = await API.addProduct(formData)
      }

      this.submitOkLoading = false
      this.submitFormVisible = false
      const { code } = response
      if (code === 1) {
        this.$message({
          message: `${this.submitFormTip}成功`,
          type: 'success'
        })
        window.setTimeout(() => this.$router.push({path: '/index/product'}), 100) // 跳转回商品列表页面
      } else {
        if (code === -1) {
          const { msg } = response
          this.$message.error(msg)
        } else {
          this.$message.error(ErrorConfig[code])
        }
      }
    },
    validateProfit (value, elementName) {
      if (!Number.parseFloat(value)) { // 非数字
        if (parseFloat(value) !== 0) {
          this.formData[elementName] = null
          this.$message.error('请输入正确的数值')
          return false
        }
      } else { // 数字
        if (value < 0) {
          this.formData[elementName] = null
          this.$message.error('请输入大于0的数值')
          return false
        }
        if (value > 20) {
          this.formData[elementName] = null
          this.$message.error('您输入的数值太大了')
          return false
        }
      }
    },
    onChangeTicket (e) {
      const selected = this.ticketList.find(item => {
        return item.id === e
      })
      this.specConfigForm.ticketTxt = selected.name
    }
  },
  components: {
    MainHeader,
    SpecListTable
  }
}
</script>

<style scoped lang="scss">
  .clearfix {
    display: block;
    &:after {
      display: block;
      content: ".";
      height: 0;
      line-height: 0;
      clear: both;
      visibility: hidden;
    }
  }
  .el-form-item {
    width: auto;
    max-width: 800px;
  }
  .add_input_wrapper {
    box-sizing: border-box;
    padding: 20px 20px 0;
    .el-form {
      box-sizing: border-box;
      padding: 40px;
      border-radius: 6px;
      background: #fff;
    }
  }
  .avatar-uploader {
    .avatar-uploader-icon {
      display: block;
      width: 120px;
      height: 120px;
      font-size: 28px;
      line-height: 120px;
      text-align: center;
      color: #8c939d;
      border: 1px dashed #d9d9d9;
      &:hover {
        border-color: #409EFF;
      }
    }
  }

  .item_img_upload_wrapper, .detail_img_upload_wrapper {
    ul {
      margin: 0;
      padding: 0;
      list-style: none;
      @extend .clearfix;
      li {
        float: left;
        margin: 0 20px 10px 0;
      }
    }
    .pci_tip {
      font-size: 12px;
      color: #87898b;
    }
  }
  .item_img_upload_wrapper {
    .add_item_pic_btn, .a_item_pic_block {
      width: 100px;
      height: 100px;
    }
  }
  .detail_img_upload_wrapper {
    .add_item_pic_btn, .a_item_pic_block {
      width: 200px;
      height: 100px;
    }
  }
  .a_item_pic_block {
    position: relative;
    &:hover {
      .hover_delete {
        display: block;
      }
    }
    .hover_delete {
      display: none;
      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      background: rgba(0, 0, 0, .3);
      .el-button {
        position: absolute;
        top: 50%;
        left: 50%;
        -webkit-transform: translate(-50%, -50%);
        -moz-transform: translate(-50%, -50%);
        -ms-transform: translate(-50%, -50%);
        -o-transform: translate(-50%, -50%);
        transform: translate(-50%, -50%);
      }
    }
  }
</style>
